/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    Text,
    ScrollView,
    TouchableWithoutFeedback,
    Animated,
    DeviceEventEmitter
} from 'react-native'
import Toast from 'react-native-simple-toast'
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'

import NavBar from '../../components/NavBarView'
import {
    FormEvent,
    FormStatus,
    PassportField,
    SubmitBtn
} from '../../components/Form'
import Constants from '../../config/Constants'
import PassportService from '../../services/Passport'

let _self = null;
let _timer = null;

const tabs = {
    LOGIN: 'login',
    REGISTER: 'register'
};

const validRule = {
    login: {
        login_name: {
            required: true,
            regExp: /1\d{10}/,
            errorMsg: '请输入11位合法手机号码'
        },
        password: {
            required: true
        }
    },
    register: {
        user_name: {
            required: true,
            regExp: /[\u4e00-\u9fa5]{2,10}/,
            errorMsg: '请输入2-10位合法联系人姓名'
        },
        login_name: {
            required: true,
            regExp: /1\d{10}/,
            errorMsg: '请输入11位合法手机号码'
        },
        mobile_code: {
            required: true,
            regExp: /\d{6}/,
            errorMsg: '请输入6位数字手机验证码'
        },
        password: {
            required: true,
            regExp: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            errorMsg: '请输入6-20位数字字母组合密码'
        },
        check: {
            required: true,
        }
    }
};

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;

        //挂载前计算tabLine的left
        const posLeft = this.props.navigation.state.params ?
            this.props.navigation.state.params.tab === tabs.REGISTER ?
                layout.MAX_WIDTH / 2 :
                0 :
            0;
        this.state = {
            tabLinePosLeft: new Animated.Value(posLeft),
            formStatus: FormStatus.EDIT,
            login: {
                login_name: '',
                password: ''
            },
            register: {
                user_name: '',
                login_name: '',
                mobile_code: '',
                password: '',
                check: ''
            },
            canSend: true,
            sendText: ''
        }
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    componentWillUnmount() {
        clearInterval(_timer);
    }

    //跳转封装
    skip(route, params) {
        _self.props.navigation.navigate(route, params ? params : {});
    }

    //tab切换
    toggle(tab) {
        if (_self.state.formStatus !== FormStatus.SUBMITTING) {
            switch (tab) {
                case tabs.LOGIN:
                    _self.refs['form_scroll'].scrollTo({
                        x: 0
                    });
                    Animated.timing(_self.state.tabLinePosLeft, {
                        duration: 300,
                        toValue: 0
                    }).start(() => {
                        _self.formReset()
                    });
                    break;
                case tabs.REGISTER:
                    _self.refs['form_scroll'].scrollToEnd();
                    Animated.timing(_self.state.tabLinePosLeft, {
                        duration: 300,
                        toValue: layout.MAX_WIDTH / 2
                    }).start(() => {
                        _self.formReset()
                    });
                    break;
                default:
                    _self.refs['form_scroll'].scrollTo({
                        x: 0
                    });
                    Animated.timing(_self.state.tabLinePosLeft, {
                        duration: 300,
                        toValue: 0
                    }).start();
            }
        }
    }

    //登录事件
    async login() {
        const valid = FormEvent.isValid(validRule[tabs.LOGIN], _self.state[tabs.LOGIN]);
        if (valid.result) {
            _self.setState({
                formStatus: FormStatus.SUBMITTING
            });
            const {result, message} = await PassportService.login({params: _self.state.login});
            if (result) {
                DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
                _self.props.navigation.goBack();
            }
            Toast.show(message);
            _self.formReset();
        } else {
            Toast.show(valid.message);
        }
    }

    //登录事件
    async register() {
        const valid = FormEvent.isValid(validRule[tabs.REGISTER], _self.state[tabs.REGISTER]);
        if (valid.result) {
            _self.setState({
                formStatus: FormStatus.SUBMITTING
            });
            const {result, message} = await PassportService.register({params: _self.state[tabs.REGISTER]});
            if (result) {
                DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
                _self.props.navigation.goBack();
            }
            Toast.show(message);
            _self.formReset();
        } else {
            Toast.show(valid.message);
        }
    }

    //发送事件
    async send() {
        //判断是否可以发送
        if (_self.state.canSend) {
            //重置倒计时
            let times = Constants.SMS_INTERVAL;
            clearInterval(_timer);
            //校验注册电话
            const login_name = _self.state.register.login_name;
            if (validRule.register.login_name.regExp.test(login_name)) {
                //禁用发送事件
                _self.setState({canSend: false});
                //异步发送事件
                const {result, message} = await PassportService.registerSend({params: {login_name}});
                if (result) {
                    //倒计时
                    _timer = setInterval(() => {
                        times--;
                        if (times > 0) {
                            _self.setState({
                                sendText: times + '秒'
                            })
                        } else {
                            //倒计时结束 恢复发送事件并清空sendText
                            _self.setState({
                                sendText: '',
                                canSend: true
                            })
                        }
                    }, 1000);
                } else {
                    //恢复发送事件并toast
                    _self.setState({canSend: true});
                    Toast.show(message);
                }
            } else {
                Toast.show(validRule.register.login_name.errorMsg);
            }
        }
    }

    //input改变触发
    inputChange(form, key, value) {
        let temp = _self.state;
        temp[form][key] = value;
        _self.setState(temp, () => {
            if (_self.state.formStatus !== FormEvent.isCompleted(validRule[form], _self.state[form])) {
                _self.setState({
                    formStatus: FormEvent.isCompleted(validRule[form], _self.state[form])
                })
            }
        });
    }

    //重置表单
    formReset() {
        const login = {
            login_name: '',
            password: ''
        }, register = {
            user_name: '',
            login_name: '',
            mobile_code: '',
            password: '',
            check: ''
        };
        _self.setState({
            formStatus: FormStatus.EDIT,
            login, register
        })
    }

    agreementCheck() {
        const check = _self.state.register.check ? '' : '01';
        _self.inputChange(tabs.REGISTER, 'check', check);
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this}/>
                <View style={styles.container}>
                    <Image
                        resizeMode={'contain'}
                        source={require('../../sources/image_demand_banner.png')}
                        style={[base.columnCC, styles.topBox]}>
                        <View style={[base.columnCC, styles.topLogo]}>
                            <Image
                                resizeMode={'contain'}
                                style={styles.topLogoIcon}
                                source={require('../../sources/image_global_logo&text.png')}/>
                        </View>
                        <View style={[base.rowCC, styles.tabBox]}>
                            <TouchableWithoutFeedback onPress={() => this.toggle(tabs.LOGIN)}>
                                <View style={[base.rowCC, styles.tabItem]}>
                                    <Text allowFontScaling={false} style={styles.tabText}>登录</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback onPress={() => this.toggle(tabs.REGISTER)}>
                                <View style={[base.rowCC, styles.tabItem]}>
                                    <Text allowFontScaling={false} style={styles.tabText}>注册</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <Animated.View ref="tab_line" style={[styles.tabLine, {left: this.state.tabLinePosLeft}]}/>
                        </View>
                    </Image>
                    <ScrollView
                        onContentSizeChange={() => {
                            //formScroll完全挂载后判断滑动
                            if (this.props.navigation.state.params && this.props.navigation.state.params.tab === tabs.REGISTER) {
                                this.refs['form_scroll'].scrollToEnd({animated: false})
                            }
                        }}
                        scrollEnabled={false}
                        ref="form_scroll"
                        pagingEnabled={true}
                        showsHorizontalScrollIndicator={false}
                        keyboardShouldPersistTaps="handled"
                        keyboardDismissMode="on-drag"
                        horizontal={true}
                        style={styles.formBox}>
                        <View style={styles.loginBox}>
                            <PassportField
                                keyboardType="number-pad"
                                inputValue={this.state.login.login_name}
                                control={this.state.formStatus}
                                maxLength={11}
                                placeholder="请输入手机号码"
                                onChangeText={(text) => this.inputChange(tabs.LOGIN, 'login_name', text)}
                                icon={require('../../sources/icon_passport_phone.png')}/>
                            <PassportField
                                inputValue={this.state.login.password}
                                control={this.state.formStatus}
                                maxLength={20}
                                secureTextEntry={true}
                                rightBtnEvent={() => this.skip('Forgot')}
                                rightBtnText="忘记密码"
                                rightBtnShow={true}
                                onChangeText={(text) => this.inputChange(tabs.LOGIN, 'password', text)}
                                placeholder="请输入登录密码"
                                icon={require('../../sources/icon_passport_password.png')}/>
                            <SubmitBtn
                                control={this.state.formStatus}
                                text="登录"
                                onPress={() => this.login()}/>
                        </View>
                        <KeyboardAwareScrollView style={styles.registerBox}>
                            <PassportField
                                inputValue={this.state.register.user_name}
                                control={this.state.formStatus}
                                maxLength={10}
                                placeholder="请输入联系人姓名"
                                onChangeText={(text) => this.inputChange(tabs.REGISTER, 'user_name', text)}
                                icon={require('../../sources/icon_passport_username.png')}/>
                            <PassportField
                                keyboardType="number-pad"
                                inputValue={this.state.register.login_name}
                                control={this.state.formStatus}
                                maxLength={11}
                                onChangeText={(text) => this.inputChange(tabs.REGISTER, 'login_name', text)}
                                placeholder="请输入手机号码"
                                icon={require('../../sources/icon_passport_phone.png')}/>
                            <PassportField
                                keyboardType="number-pad"
                                inputValue={this.state.register.mobile_code}
                                control={this.state.formStatus}
                                maxLength={6}
                                rightBtnEvent={() => this.state.canSend ? this.send() : {}}
                                rightBtnText={this.state.sendText || '获取验证码'}
                                rightBtnShow={true}
                                rightBtnTextStyle={{
                                    width: layout.width(180),
                                    textAlign: 'center',
                                    color: this.state.canSend ? layout.MAIN_COLOR : layout.FORM_AUX_FONT_COLOR
                                }}
                                placeholder="请输入短信验证码"
                                onChangeText={(text) => this.inputChange(tabs.REGISTER, 'mobile_code', text)}
                                icon={require('../../sources/icon_passport_valid.png')}/>
                            <PassportField
                                inputValue={this.state.register.password}
                                control={this.state.formStatus}
                                maxLength={20}
                                secureTextEntry={true}
                                onChangeText={(text) => this.inputChange(tabs.REGISTER, 'password', text)}
                                placeholder="请设置6-20位数字字母组合密码"
                                icon={require('../../sources/icon_passport_password.png')}/>
                            <SubmitBtn
                                control={this.state.formStatus}
                                text="注册"
                                onPress={() => this.register()}/>
                            <View style={[base.rowCC, styles.agreementBox]}>
                                <TouchableWithoutFeedback onPress={() => this.agreementCheck()}>
                                    <View style={base.rowCC}>
                                        <Image
                                            source={this.state.register.check ? require('../../sources/icon_login_check.png') : require('../../sources/icon_login_check_un.png')}
                                            style={styles.agreementCheck}
                                            resizeMode="contain"/>
                                        <Text style={styles.agreementText}>我已阅读并同意</Text>
                                    </View>
                                </TouchableWithoutFeedback>
                                <TouchableWithoutFeedback onPress={() => this.skip('Agreement', {id: '1'})}>
                                    <View>
                                        <Text style={styles.agreementTextSub}>《用户注册协议》</Text>
                                    </View>
                                </TouchableWithoutFeedback>
                            </View>
                        </KeyboardAwareScrollView>
                    </ScrollView>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignSelf: 'stretch',
    },
    topBox: {
        width: layout.MAX_WIDTH,
        height: layout.height(270),
        backgroundColor: layout.MAIN_AUX_COLOR
    },
    topLogo: {
        flex: 1,
    },
    topLogoIcon: {
        width: layout.width(294),
        height: layout.height(80)
    },
    tabBox: {},
    tabItem: {
        flex: 1,
        paddingVertical: layout.height(34)
    },
    tabText: {
        color: layout.MAIN_COLOR,
        fontSize: layout.font(32)
    },
    tabLine: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        width: layout.MAX_WIDTH / 2,
        height: layout.height(6),
        backgroundColor: layout.MAIN_COLOR
    },
    formBox: {},
    loginBox: {
        width: layout.MAX_WIDTH,
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE
    },
    registerBox: {
        width: layout.MAX_WIDTH,
        alignSelf: 'stretch',
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE
    },
    agreementBox: {
        marginTop: layout.height(60)
    },
    agreementCheck: {
        marginRight: layout.width(12),
        width: layout.width(24),
        height: layout.height(24)
    },
    agreementText: {
        fontSize: layout.font(24),
        color: layout.FORM_FONT_COLOR
    },
    agreementTextSub: {
        fontSize: layout.font(24),
        color: layout.MAIN_COLOR
    }
})

//路由
const Login = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'Login',
    sign: false
};

export default Login;